package com.formiaomiao.demain.service.impl;

import com.formiaomiao.demain.dao.DiscussDao;
import com.formiaomiao.demain.dao.UserDao;
import com.formiaomiao.demain.model.DiscussBean;
import com.formiaomiao.demain.model.Result;
import com.formiaomiao.demain.model.ResultData;
import com.formiaomiao.demain.service.DiscussService;
import com.formiaomiao.demain.utils.ResultUtil;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(value = "discussService")
public class DiscussServiceImpl implements DiscussService {

    @Autowired
    DiscussDao discussDao;
    @Autowired
    UserDao userDao;

    @Transactional(value = "demain")
    @Override
    public Result<String> InsertDiscuss(DiscussBean discussBean) {
        if (discussDao.InsertDiscuss(discussBean) == 0) {
            return ResultUtil.error(400, "评论失败");
        } else {
            return ResultUtil.success("评论成功");
        }
    }

    @Transactional(value = "demain")
    @Override
    public Result<String> DeleteDiscuss(DiscussBean discussBean) {
        if (discussDao.DeleteDiscuss(discussBean) == 0) {
            return ResultUtil.error(400, "删除失败");
        } else {
            return ResultUtil.success("删除成功");
        }
    }

    @Override
    public Result<DiscussBean> SelectDiscuss(String comid, int pageNum, int pageSize) {
        if (discussDao.SelectDiscuss(comid).size() == 0) {
            return ResultUtil.error(400, "暂没有评论信息");
        } else if (discussDao.SelectDiscuss(comid).size() > 0) {
            PageHelper.startPage(pageNum, pageSize);
            List<DiscussBean> list = discussDao.SelectDiscuss(comid);
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setUserBean(userDao.selectUser(list.get(i).getFromid()));
                if (list.get(i).getToid() != null) {
                    list.get(i).setToUserBean(userDao.selectUser(list.get(i).getToid()));
                }
            }
            ResultData result = new ResultData(pageNum, pageSize, list);
            return ResultUtil.success(result);
        } else {
            return ResultUtil.error(400, "获取失败");
        }
    }
}
